package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 赵雨强
 * @create 2021/4/30 6:47
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;


    @Value("${server.port}")
    private String serverPort;

    /*
    * POST请求中，通过HttpEntity传递的参数，必须要在请求头中声明数据的类型Content-Type，SpringMVC通过使用
     *HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据，然后绑定到相应的bean上。*/
    @PostMapping(value = "/payment/create")
    public CommonResult<Integer> create(@RequestBody  Payment payment){
        int result = paymentService.create(payment);
        log.info("**************插入结果："+result);
        if(result > 0){
            return new CommonResult<>(200,"插入成功,端口号"+serverPort,result);
        }else {
            return new CommonResult<>(200,"插入失败",null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> create(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("**************插入结果："+paymentById.toString());
        if(paymentById != null){
            return new CommonResult<>(200,"查询成功,端口号"+serverPort,paymentById);
        }else {
            return new CommonResult<>(200,"未查询到"+id,null);
        }
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }


    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        //暂停几秒钟，延迟Feign
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return serverPort;
    }

}
